package pdf.IText;

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;

/**
 * 页眉
 */
public class PdfHeaderMarker implements IEventHandler {

    private PdfFont pdfFont;
    private String title;

    public PdfHeaderMarker(PdfFont pdfFont, String title) {
        this.pdfFont = pdfFont;
        this.title = title;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        int pageNumber = pdf.getPageNumber(page);
        if (pageNumber != 1) { // 封面不展示页眉页脚
            Rectangle pageSize = page.getPageSize();
            PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), pdf);
            Canvas canvas = new Canvas(pdfCanvas, pageSize);
            float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
            float y = pageSize.getTop() - 25;
            Paragraph p = new Paragraph(title)
                .setFontSize(12)
                .setFont(pdfFont);
            // 顶部中间位置
            canvas.showTextAligned(p, x, y, TextAlignment.CENTER);
            canvas.close();
        }
    }

}
